#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Filename: case_associated_requirements.py
# Author: ChenChangSong
# Date: 2025-08-24

"""
功能描述: 创建需求与测试用例关联关系(目前403)
https://open.tapd.cn/document/api-doc/API%E6%96%87%E6%A1%A3/api_reference/story/create_story_tcase.html
"""

import sys
import os
import time
from comm.common_code import *


def create_test_cases_association_requirements(story_id, tcase_id, max_retries=5):
    """
    创建需求与测试用例关联关系
    :param story_id: 需求ID
    :param tcase_id: 用例ID
    :param max_retries: 最大重试次数
    :return: (响应状态码, 响应内容)
    """
    excel_data = get_excel_data()
    time.sleep(0.5)
    url = f"https://api.tapd.cn/stories/add_story_tcase"
    payload = {
        "access_token": excel_data['access_token'], 
        'workspace_id': excel_data['项目ID'],  # 使用配置中的项目ID
        'story_id': story_id,
        'tcase_id': tcase_id
    }

    # 添加重试机制
    retry_count = 0
    while retry_count < max_retries:
        # 使用data参数自动编码为x-www-form-urlencoded格式
        logger.info(f'创建需求{story_id}与测试用例{tcase_id}关联关系和↓↓↓=================================================↓↓↓')
        response_code, response = api_request(method='POST', url=url, headers={}, data=payload)
        logging.info(f"响应内容: {response}")
        logger.info(f'↑↑↑=================================================↑↑↑')
        
        if response_code == 200:
            # 请求成功，返回结果
            return response_code, response
        elif response_code == 429:
            # API限流，等待后重试
            wait_time = (2 ** retry_count) + random.random()
            logger.warning(f"API限流，等待 {wait_time:.2f} 秒后重试 (尝试 {retry_count + 1}/{max_retries})")
            time.sleep(wait_time)
            retry_count += 1
        else:
            # 其他错误，直接返回
            return response_code, response
    
    # 达到最大重试次数仍然失败
    logger.error(f"创建需求 {story_id} 与测试用例 {tcase_id} 关联关系失败，已达最大重试次数")
    return response_code, response

if __name__ == "__main__":
    # 【示例】个人中心:1148433040001000062
    # 【示例】订单管理:1148433040001000061
    # 用例：规划目录》简单用例62：1148433040001000139
    create_test_cases_association_requirements('1166606973001058964', '1166606973001110928')